import base64
import time
from flask import Flask, render_template, request, make_response, send_file, send_from_directory, session, redirect, \
    Response
from flask_cors import *
import os
import pymysql

app = Flask(__name__)
CORS(app, spports_credentials=True)
app.config["SECRET_KEY"] = 'TPmi4aLWRbyVq8zu9v82dWYW1'

conn = pymysql.connect(host='localhost', user="Sunzl", passwd="123456", port=3306, db="test")
cur = conn.cursor()


@app.route('/', methods=['POST', 'GET'])
def hello_world():
    return render_template('index.html')


@app.route('/getName', methods=['POST', 'GET'])
def get_name():
    name = request.cookies.get('username')
    return {
        "name":name
    }

@app.route('/image', methods=['POST', 'GET'])
def image():
    path = request.args["path"]
    print(path)
    with open(path,'rb') as f:
        img =f.read()
        f.close()
    return Response(img,mimetype="png")


@app.route('/login', methods=['POST', 'GET'])
def login():
    return render_template('index.html')


@app.route('/file-list', methods=['POST', 'GET'])
def fileList():
    return render_template('File.html')


@app.route('/file-list-sent', methods=['POST', 'GET'])
def collect():
    path = request.args['path']
    print(path)
    name = request.cookies.get("username")
    path2 = "E:\main" + "\\" + name
    if path == "":
        path = path2
    if os.path.isfile(path):
        change(path)
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read()
            f.close()
            file = {"content": content}
        print(file)
        return file
    listFile = []
    if path != path2:
        Pre_path = path.split("\\")
        Pre_path.pop()
        Pre_path = "\\".join(Pre_path)
        dict_path = {"name": "..", "path": Pre_path}
        listFile.append(dict_path)
    for filename in os.listdir(path):
        dictFile = {"name": filename, "path": path + "\\" + filename}
        file_name, file_extension = os.path.splitext(filename)
        if os.path.isdir(path + "\\" + filename):
            dictFile["fold"] = True
            dictFile["file-type"] = "fold"
        elif file_extension in ['jpg', 'bmp', 'png', 'jpeg', 'jfif']:
            dictFile["fold"] = False
            dictFile["file-type"] = "img"
        else:
            dictFile["fold"] = False
            dictFile["file-type"] = "file"
        listFile.append(dictFile)
    fileList = {"children": listFile}
    return fileList


@app.route('/file', methods=['POST', 'GET'])
def file_manage():
    return {
        "name": "root",
        "root": r"E:\大三课程\java\实验报告\A",
        "fold": True
    }


@app.route('/fileDown', methods=['POST', 'GET'])
def file_down():
    down_path = request.args["path"]
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    file_dir_file = os.path.split(down_path)
    object_path = down_path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name, object_path,"down-file",Time)
    cur.execute(insert)
    conn.commit()
    return send_from_directory(file_dir_file[0], file_dir_file[1], as_attachment=True)


@app.route('/edit_file', methods=['POST', 'GET'])
def edit_file():
    file_path = request.json['path']
    file_content = request.json['content']
    print(file_content)
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    object_path = file_path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name,object_path,"edit",Time)
    cur.execute(insert)
    conn.commit()
    with open(file_path, 'w', encoding="utf-8") as f:
        f.write(file_content)
        f.close()
    return {
        "name": "root",
        "root": r"",
        "fold": True
    }


@app.route('/delete-file', methods=['POST', 'GET'])
def Del_file():
    listFile = []
    path = request.args['path']
    os.remove(path)
    new_path = path.split("\\")
    new_path.pop()
    new_path = "\\".join(new_path)
    name2 = request.cookies.get("username")
    path2 = "E:\main" + "\\" + name2
    if path == "":
        path = path2
    if new_path != path2:
        Pre_path = new_path.split("\\")
        Pre_path.pop()
        Pre_path = "\\".join(Pre_path)
        dict_path = {"name": "..", "path": Pre_path}
        listFile.append(dict_path)
    for filename in os.listdir(new_path):
        dictFile = {"name": filename, "path": new_path + "\\" + filename}
        file_name, file_extension = os.path.splitext(filename)
        if os.path.isdir(new_path + "\\" + filename):
            dictFile["fold"] = True
            dictFile["file-type"] = "fold"
        elif file_extension in ['jpg', 'bmp', 'png', 'jpeg', 'jfif']:
            dictFile["fold"] = False
            dictFile["file-type"] = "img"
        else:
            dictFile["fold"] = False
            dictFile["file-type"] = "file"
        listFile.append(dictFile)
    fileList = {"children": listFile}
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    object_path = path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name,object_path,"delete-file",Time)
    cur.execute(insert)
    conn.commit()
    return fileList



@app.route('/create-file', methods=['POST', 'GET'])
def create_file():
    listFile = []
    name = request.args['name']
    path = request.args['path']
    name2 = request.cookies.get("username")
    path2 = "E:\main" + "\\" + name2
    if path == "":
        path = path2
    os.chdir(path)
    with open(name, 'w')as newFile:
        newFile.close()
    if path != path2:
        Pre_path = path.split("\\")
        Pre_path.pop()
        Pre_path = "\\".join(Pre_path)
        dict_path = {"name": "..", "path": Pre_path}
        listFile.append(dict_path)
    for filename in os.listdir(path):
        dictFile = {"name": filename, "path": path + "\\" + filename}
        file_name, file_extension = os.path.splitext(filename)
        if os.path.isdir(path + "\\" + filename):
            dictFile["fold"] = True
            dictFile["file-type"] = "fold"
        elif file_extension in ['jpg', 'bmp', 'png', 'jpeg', 'jfif']:
            dictFile["fold"] = False
            dictFile["file-type"] = "img"
        else:
            dictFile["fold"] = False
            dictFile["file-type"] = "file"
        listFile.append(dictFile)
    fileList = {"children": listFile}
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    object_path = path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name, object_path,
                                                                                                            "create-file",
                                                                                                            Time)
    cur.execute(insert)
    conn.commit()
    return fileList


@app.route('/create-folder', methods=['POST', 'GET'])
def create_folder():
    listFile = []
    name = request.args['name']
    path = request.args['path']
    name2 = request.cookies.get("username")
    path2 = "E:\main" + "\\" + name2
    if path == "":
        path = path2
    print(path)
    print(name)
    os.chdir(path)
    os.mkdir(name)
    if path != path2:
        Pre_path = path.split("\\")
        Pre_path.pop()
        Pre_path = "\\".join(Pre_path)
        dict_path = {"name": "..", "path": Pre_path}
        listFile.append(dict_path)
    for filename in os.listdir(path):
        dictFile = {"name": filename, "path": path + "\\" + filename}
        file_name, file_extension = os.path.splitext(filename)
        if os.path.isdir(path + "\\" + filename):
            dictFile["fold"] = True
            dictFile["file-type"] = "fold"
        elif file_extension in ['jpg', 'bmp', 'png', 'jpeg', 'jfif']:
            dictFile["fold"] = False
            dictFile["file-type"] = "img"
        else:
            dictFile["fold"] = False
            dictFile["file-type"] = "file"
        listFile.append(dictFile)
    fileList = {"children": listFile}
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    object_path = path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name, object_path,
                                                                                                            "create-folder",
                                                                                                            Time)
    cur.execute(insert)
    conn.commit()
    return fileList


@app.route('/receive-file', methods=['POST', 'GET'])
def receive():
    path = request.form["path"]
    listFile = []
    file = request.files["file-sent"]
    name = request.cookies.get("username")
    path2 = "E:\main" + "\\" + name
    if path == "":
        path = path2
    file.save(path + "\\" + file.filename)
    if path != path2:
        Pre_path = path.split("\\")
        Pre_path.pop()
        Pre_path = "\\".join(Pre_path)
        dict_path = {"name": "..", "path": Pre_path}
        listFile.append(dict_path)
    for filename in os.listdir(path):
        dictFile = {"name": filename, "path": path + "\\" + filename}
        if os.path.isdir(path + "\\" + filename):
            dictFile["fold"] = True
        else:
            dictFile["fold"] = False
        listFile.append(dictFile)
    fileList = {"children": listFile}
    name = request.cookies.get("username")
    Time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    object_path = path.split("\\")
    object_path = "/".join(object_path)
    insert = "insert into user_rz (user_name,object,operation,data) VALUES('{0}','{1}','{2}','{3}')".format(name, object_path,
                                                                                                            "up-load-file",
                                                                                                            Time)
    cur.execute(insert)
    conn.commit()
    return fileList


@app.route('/userLogin', methods=['POST', 'GET'])
def userLogin():
    if request.method == 'GET':
        print("GET")
        # 判断是否已经在登录状态上:判断session中是否有uname的值
        if 'username' in session:
            # 已经登录了，直接去往首页
            return redirect('/file-list')
        else:
            # 没有登录，继续向下判断cookie
            if 'username' in request.cookies:
                # 曾经记住过密码,取出值保存进session
                name = request.cookies.get('username')
                session['username'] = name
                return redirect('/file-list')
            else:
                # 　之前没有登录过,去往登录页
                return render_template('index.html')
    else:
        print("POST")
        # 先处理登录,登录成功继续则保存进session,否则回到登录页
        print(request.form['username'])
        name = request.form['username']
        print(name)
        password = request.form['password']
        password = password.encode("utf-8")
        password = base64.encodebytes(password)
        password = password.decode()
        selectByName = "select password,root_path from user where user_name='{0}'".format(name)
        cur.execute(selectByName)
        row = cur.fetchall()
        try:
            tip = row[0][0]
            path = row[0][1]
        except:
            return render_template('index.html', msg="用户名或者密码")
        # 本文默认正确的账号密码为:admin
        if password == tip:
            print("声明重定向到首页的对象")
            # 声明重定向到首页的对象
            resp = redirect('/file-list')
            # 登录成功：先将数据保存进session
            session['username'] = name
            print("session")
            # 判断是否要记住密码
            resp.set_cookie('username', name, 60 * 60 * 1)
            return resp
        else:
            # 登录失败
            return redirect('/login')


@app.route('/register', methods=['POST', 'GET'])
def register():
    name = request.form["register-name"]
    print(name)
    password = request.form["register-password"]
    print(password)
    password = password.encode("utf-8")
    password = base64.encodebytes(password)
    password = password.decode()
    path = r"E:/main" + "/" + name
    print(path)
    os.mkdir(path)
    insert_sql = "insert into user (user_name,root_path,password) VALUES('{0}','{1}','{2}')".format(name, path,
                                                                                                    password)
    cur.execute(insert_sql)
    conn.commit()
    return render_template('index.html')


def change(path):
    with open(path, 'r') as file:
        content = file.read()
        file.close()
    with open(path, 'w') as file2:
        file2.write(content)
        file2.close()


if __name__ == '__main__':
    app.run()
